<?php
namespace Controllers;

use Services\GreenWaveCalculator;
use Models\GreenWaveSection;
use Models\Intersection;

/**
 * 绿波控制器类
 */
class GreenWaveController {
    private $calculator;
    private $section;
    private $intersection;
    
    public function __construct() {
        $this->calculator = new GreenWaveCalculator();
        $this->section = new GreenWaveSection();
        $this->intersection = new Intersection();
    }
    
    /**
     * 获取所有路段列表
     */
    public function getSections() {
        try {
            $sections = $this->section->getAllSections();
            return $this->success($sections);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 获取路段详情
     */
    public function getSectionDetail($id) {
        try {
            $section = $this->section->getSectionById($id);
            if (!$section) {
                return $this->error("路段不存在");
            }
            
            // 获取路段路口
            $intersections = $this->section->getSectionIntersections($id);
            $section['intersections'] = $intersections;
            
            // 获取当前效率
            $section['efficiency'] = $this->section->getSectionEfficiency($id);
            
            return $this->success($section);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 创建新路段
     */
    public function createSection() {
        try {
            $data = $this->getRequestData();
            
            // 验证必要字段
            $required = ['name', 'start_intersection_id', 'end_intersection_id', 'direction', 'design_speed'];
            foreach ($required as $field) {
                if (!isset($data[$field])) {
                    return $this->error("缺少必要字段: {$field}");
                }
            }
            
            // 验证路口是否存在
            $startIntersection = $this->intersection->getIntersectionById($data['start_intersection_id']);
            $endIntersection = $this->intersection->getIntersectionById($data['end_intersection_id']);
            
            if (!$startIntersection || !$endIntersection) {
                return $this->error("起点或终点路口不存在");
            }
            
            // 创建路段
            $this->section->addSection($data);
            
            return $this->success(["message" => "路段创建成功"]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 更新路段信息
     */
    public function updateSection($id) {
        try {
            $data = $this->getRequestData();
            
            // 检查路段是否存在
            $section = $this->section->getSectionById($id);
            if (!$section) {
                return $this->error("路段不存在");
            }
            
            // 更新路段
            $this->section->updateSection($id, $data);
            
            return $this->success(["message" => "路段更新成功"]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 删除路段
     */
    public function deleteSection($id) {
        try {
            // 检查路段是否存在
            $section = $this->section->getSectionById($id);
            if (!$section) {
                return $this->error("路段不存在");
            }
            
            // 删除路段
            $this->section->deleteSection($id);
            
            return $this->success(["message" => "路段删除成功"]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 计算绿波配时方案
     */
    public function calculateTimingPlan($sectionId) {
        try {
            $data = $this->getRequestData();
            
            // 计算配时方案
            $result = $this->calculator->calculateTimingPlan($sectionId, $data);
            
            return $this->success($result);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 获取请求数据
     */
    private function getRequestData() {
        return json_decode(file_get_contents('php://input'), true) ?? [];
    }
    
    /**
     * 成功响应
     */
    private function success($data) {
        return $this->response([
            'code' => 0,
            'message' => 'success',
            'data' => $data
        ]);
    }
    
    /**
     * 错误响应
     */
    private function error($message, $code = 1) {
        return $this->response([
            'code' => $code,
            'message' => $message,
            'data' => null
        ]);
    }
    
    /**
     * 输出响应
     */
    private function response($data) {
        header('Content-Type: application/json');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }
} 